package com.wuyoucar.util;

import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class mailUtils {
    private static String from;//发送人
    private static String to;//接收人
    private static Properties properties;
    private static Session session;//邮件会话
    private static Message message;
    //验证密码和账号
    private static  Authenticator authenticator= new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("1065064621@qq.com","nyuydtwiahshbbjb");
        }
    };
    static {
        from="1065064621@qq.com";
        properties=new Properties();
        properties.setProperty("mail.host","smtp.qq.com");
        properties.setProperty("mail.smtp.auth","true");
        session=Session.getDefaultInstance(properties,authenticator);
        message=new MimeMessage(session);
    }
    //调用这个方法发送
    public static String sendMessage(String to){
        String checkedCode=null;
        try {
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
            message.setSubject("欢迎使用无忧车险");
           checkedCode=(int) (Math.random()*1000000)+"";
          message.setText("邮箱绑定验证码为:"+checkedCode);
          Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return checkedCode;
    }
}
